package info.wegosoft.android.activity;

import info.wegosoft.R;
import info.wegosoft.android.model.MBlog;
import info.wegosoft.android.model.Platform;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ZoomControls;

/**  
 * Filename:    ImageViewActivity.java 
 * Package:     info.wegosoft.android.activity 
 * Description: TODO(这里用一句话描述这个类的作用)
 * Copyright:   Copyright (c) wegosoft.info 2011  
 * @author:     李辉 
 * email:       fzlihui@gmail.com
 * @version:    1.0  
 * Create at:   2011-6-26 下午05:40:08  
 */
public class ImageViewActivity extends Activity {

	private ImageView imageView;
	//原始的图片
	private Bitmap srcBitmap;
	//实际显示的图片
	private Bitmap bitmap;
	//显示的宽高比例
	private float scale_size = 1.0f;
	private ProgressDialog progressDialog;
	private String imageURL;
	private MBlog mblog;
	private UIHandler handler;
	private boolean isSourceImage;
	private String addCacheFlag = "";
	private static final String ORIGINAL_PIC_CACHE_DIR = "original";
	private String timeStamp;
	
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.image_viewer);
		
		Bundle bundle = getIntent().getExtras();
		
		imageURL = bundle.getString("imageURL");
		
		isSourceImage = bundle.getBoolean("sourceImage");
		
		mblog = (MBlog) bundle.getSerializable("mblog");

		int platformType = this.getSharedPreferences("platform",Context.MODE_PRIVATE).getInt("type", -1);
		
		switch (platformType) {
			case Platform.SINA_PLATFORM:
				addCacheFlag = "sina";
				break;
			case Platform.TENCENT_PLATFORM:
				addCacheFlag = "tencent";
				break;
			default:
				break;
		}
		
		handler = new UIHandler();
		
		initView();
		
		loadImage();
	}

	private void initView(){
		
		//图片
		imageView = (ImageView) findViewById(R.id.mblogImage);
		
		//后退按钮
		Button imageViewBackBtn = (Button) findViewById(R.id.imageViewBackBtn);
		
		imageViewBackBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				Intent intent = new Intent();
				
				Bundle bundle = new Bundle();
				
				bundle.putSerializable("mblog", mblog);
				
				intent.putExtras(bundle);
				
				intent.setClass(ImageViewActivity.this, DetailMBlogActivity.class);
				
				startActivity(intent);
			}
		});
		
		//保存图片按钮
		Button imageViewSaveBtn = (Button) findViewById(R.id.imageViewSaveBtn);
		
		imageViewSaveBtn.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				progressDialog = ProgressDialog.show(ImageViewActivity.this, null , "正在保存图片");
				
				new Thread(){

					public void run() {
						
						try {
							if(srcBitmap == null)
								return;
							
							File dir = new File(
									Environment.getExternalStorageDirectory()
											+ getResources().getString(
													R.string.download_images_dir_path));

							if (!dir.exists())
								dir.mkdirs();

							//以时间戳命名图片
							timeStamp = new Date().getTime() + "";
							
							File picFile = new File(
									Environment.getExternalStorageDirectory()
									+ getResources().getString(
											R.string.download_images_dir_path) + timeStamp + ".jpeg");
							
							if (picFile.createNewFile()) {

								FileOutputStream out = new FileOutputStream(picFile);

								srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

								handler.sendEmptyMessage(DOWNLOAD_SUCCEED);
								
							}
							
						} catch (NotFoundException e) {
							
							e.printStackTrace();
							
							handler.sendEmptyMessage(DOWNLOAD_ERROR);
							
						} catch (FileNotFoundException e) {

							e.printStackTrace();
							
							handler.sendEmptyMessage(DOWNLOAD_ERROR);
							
						} catch (IOException e) {

							e.printStackTrace();
							
							handler.sendEmptyMessage(DOWNLOAD_ERROR);
							
						}
					}
						
				}.start();
				
			}
		});
		
		//缩放控件
		ZoomControls zc = (ZoomControls) findViewById(R.id.zc);
		
		//放大
		zc.setOnZoomInClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				//创建操作图片用的Matrix对象  
				Matrix matrix = new Matrix();

				scale_size = (float) (scale_size * 1.25);
				
				//设置缩放比例  
				matrix.postScale(scale_size, scale_size);         
				
				bitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);      
				
				handler.sendEmptyMessage(UPDATE_IMAGE);
				
			}
			
		});
		
		//缩小
		zc.setOnZoomOutClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				
				//创建操作图片用的Matrix对象  
				Matrix matrix = new Matrix();

				scale_size = (float) (scale_size * 0.75);
				
				//设置缩放比例  
				matrix.postScale(scale_size, scale_size);         
				
				bitmap = Bitmap.createBitmap(srcBitmap, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);      
				
				handler.sendEmptyMessage(UPDATE_IMAGE);
				
			}
			
		});
		
	}
	
	/**
	 * 载入图片
	 */
	private void loadImage() {

		progressDialog = ProgressDialog.show(this, null,
				"载入图片中", true);

		new Thread() {

			public void run() {

				try {
					String id;

					if (isSourceImage) {

						id = mblog.getSourceMBlog().getId();

					} else {

						id = mblog.getId();

					}

					FileInputStream in = null;

					FileOutputStream out = null;

					InputStream imageUrlStream = null;

					// 先判断本地是否有缓存，没有再下载
					File picFile = new File(
							Environment.getExternalStorageDirectory()
									+ getResources().getString(
											R.string.mblog_images_dir_path)
									+ addCacheFlag + "/" + ORIGINAL_PIC_CACHE_DIR
									+ "/" + id + ".jpeg");

					// 本地缓存存在
					if (picFile.exists()) {

						in = new FileInputStream(picFile);

						srcBitmap = BitmapFactory.decodeStream(in);

						bitmap = srcBitmap;
						// 本地缓存中不存在这张图片再下载并缓存到本地
					} else {

						URL imageUrl = new URL(imageURL);

						imageUrlStream = imageUrl.openStream();

						srcBitmap = BitmapFactory.decodeStream(imageUrlStream);

						bitmap = srcBitmap;
						
						File dir = new File(
								Environment.getExternalStorageDirectory()
										+ getResources().getString(
												R.string.mblog_images_dir_path)
										+ addCacheFlag + "/"
										+ ORIGINAL_PIC_CACHE_DIR);

						if (!dir.exists())
							dir.mkdirs();

						if (picFile.createNewFile()) {

							out = new FileOutputStream(picFile);

							srcBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);

						}

					}

					handler.sendEmptyMessage(UPDATE_IMAGE);
					
				} catch (NotFoundException e) {
					
					e.printStackTrace();
					
					handler.sendEmptyMessage(LOAD_ERROR);
					
				} catch (FileNotFoundException e) {

					e.printStackTrace();
					
					handler.sendEmptyMessage(LOAD_ERROR);
					
				} catch (MalformedURLException e) {

					e.printStackTrace();
					
					handler.sendEmptyMessage(LOAD_ERROR);
					
				} catch (IOException e) {

					e.printStackTrace();
					
					handler.sendEmptyMessage(LOAD_ERROR);
					
				}

			}
		}.start();
	}
	
	private static final int UPDATE_IMAGE = 0;
	private static final int DOWNLOAD_SUCCEED = 1;
	private static final int DOWNLOAD_ERROR = 2;
	private static final int LOAD_ERROR = 3;
	
	private class UIHandler extends Handler{
		
		public void handleMessage(Message msg) {

			// 此处可以更新主线程UI
			switch (msg.what) {
				case UPDATE_IMAGE:
					
					 if(bitmap!=null){
						 
						 imageView.setImageBitmap(bitmap);
						
					 }
					 
					 progressDialog.dismiss();
					 
					 break;

				case DOWNLOAD_SUCCEED:
					 
					 progressDialog.dismiss();
					 
					 Toast.makeText(
							ImageViewActivity.this,
							"图片已经保存到"
									+ Environment.getExternalStorageDirectory()
									+ getResources().getString(
											R.string.download_images_dir_path)
									+ timeStamp + ".jpeg", Toast.LENGTH_SHORT)
							.show();
					 
					 break;
					
				case DOWNLOAD_ERROR:
					 
					 progressDialog.dismiss();
					
					 Toast.makeText(ImageViewActivity.this, "图片保存失败", Toast.LENGTH_SHORT).show();
					 
					 break;
					 
				case LOAD_ERROR:
					
					 progressDialog.dismiss();
					 
					 Toast.makeText(ImageViewActivity.this, "载入失败", Toast.LENGTH_SHORT).show();
					 
					 break;
					 
				default:
					break;
			}	
					
		}
		
	}
}
